<template>
  <view class="study-plan-container">
    <view class="header">
      <h1>我的学习计划</h1>
      <button class="btn btn-primary" @click="showCreateModal = true">创建学习计划</button>
    </view>

    <!-- 学习统计卡片 -->
    <view class="stats-cards">
      <view class="stat-card">
        <view class="stat-icon">
          <i class="fa fa-calendar-check-o"></i>
        </view>
        <view class="stat-content">
          <view class="stat-value">{{ streakCount }}</view>
          <view class="stat-label">连续学习天数</view>
        </view>
      </view>
      <view class="stat-card">
        <view class="stat-icon">
          <i class="fa fa-book"></i>
        </view>
        <view class="stat-content">
          <view class="stat-value">{{ totalWordsLearned }}</view>
          <view class="stat-label">累计学习单词</view>
        </view>
      </view>
      <view class="stat-card">
        <view class="stat-icon">
          <i class="fa fa-clock-o"></i>
        </view>
        <view class="stat-content">
          <view class="stat-value">{{ totalStudyHours }}h</view>
          <view class="stat-label">累计学习时长</view>
        </view>
      </view>
    </view>

    <!-- 当前学习计划 -->
    <view v-if="currentPlan" class="current-plan-section">
      <view class="section-header">
        <h2>当前学习计划</h2>
        <button class="btn btn-secondary" @click="editCurrentPlan">编辑</button>
      </view>
      <view class="current-plan-card">
        <view class="plan-info">
          <h3>{{ currentPlan.name }}</h3>
          <p class="plan-description">{{ currentPlan.description }}</p>
          <view class="plan-meta">
            <span class="plan-daily-target">每日目标：{{ currentPlan.dailyTarget }} 个单词</span>
            <span class="plan-status" :class="currentPlan.status">
              {{ getStatusText(currentPlan.status) }}
            </span>
          </view>
        </view>
        <view class="plan-progress">
          <view class="progress-header">
            <span>完成进度</span>
            <span>{{ planProgress }}%</span>
          </view>
          <view class="progress-bar">
            <view class="progress-fill" :style="{ width: planProgress + '%' }"></view>
          </view>
        </view>
        <view class="plan-actions">
          <button 
            v-if="currentPlan.status !== 'completed'" 
            class="btn btn-primary"
            @click="startTodayStudy"
          >
            今日学习
          </button>
          <button 
            v-if="currentPlan.status === 'active'"
            class="btn btn-secondary"
            @click="pausePlan"
          >
            暂停计划
          </button>
          <button 
            v-if="currentPlan.status === 'paused'"
            class="btn btn-secondary"
            @click="resumePlan"
          >
            继续计划
          </button>
        </view>
      </view>
    </view>

    <!-- 历史学习计划 -->
    <view v-if="historicalPlans.length > 0" class="historical-plans-section">
      <view class="section-header">
        <h2>历史学习计划</h2>
      </view>
      <view class="plan-list">
        <view class="plan-item" v-for="plan in historicalPlans" :key="plan.id">
          <view class="plan-item-info">
            <h3>{{ plan.name }}</h3>
            <p class="plan-item-description">{{ plan.description }}</p>
            <view class="plan-item-meta">
              <span class="plan-item-period">
                {{ formatDate(plan.startDate) }} - {{ formatDate(plan.endDate) }}
              </span>
              <span class="plan-item-status" :class="plan.status">
                {{ getStatusText(plan.status) }}
              </span>
            </view>
          </view>
          <view class="plan-item-actions">
            <button class="btn btn-secondary" @click="viewPlanDetail(plan.id)">查看详情</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 创建/编辑学习计划模态框 -->
    <view class="modal" v-if="showCreateModal || showEditModal" @click.self="closeModal">
      <view class="modal-content">
        <view class="modal-header">
          <h2>{{ editingPlan ? '编辑学习计划' : '创建学习计划' }}</h2>
          <button class="close-btn" @click="closeModal">&times;</button>
        </view>
        
        <view class="modal-body">
          <view @click="savePlan">
            <view class="form-group">
              <label for="planName">计划名称</label>
              <input
                type="text"
                id="planName"
                v-model="formData.name"
                required
                placeholder="请输入学习计划名称"
              />
            </view>
            
            <view class="form-group">
              <label for="planDescription">计划描述</label>
              <textarea
                id="planDescription"
                v-model="formData.description"
                placeholder="请输入学习计划描述"
                rows="3"
              ></textarea>
            </view>
            
            <view class="form-group">
              <label for="planWordSet">选择单词集</label>
              <select id="planWordSet" v-model="formData.wordSetId" required>
                <option value="">请选择单词集</option>
                <option v-for="wordSet in availableWordSets" :key="wordSet.id" :value="wordSet.id">
                  {{ wordSet.name }} ({{ wordSet.wordCount }}个单词)
                </option>
              </select>
            </view>
            
            <view class="form-group">
              <label for="dailyTarget">每日学习目标（单词数）</label>
              <input
                type="number"
                id="dailyTarget"
                v-model.number="formData.dailyTarget"
                required
                min="1"
                max="100"
                placeholder="请输入每日学习单词数"
              />
            </view>
            
            <view class="form-group">
              <label for="startDate">开始日期</label>
              <input
                type="date"
                id="startDate"
                v-model="formData.startDate"
                required
              />
            </view>
            
            <view class="form-group">
              <label for="endDate">结束日期（可选）</label>
              <input
                type="date"
                id="endDate"
                v-model="formData.endDate"
              />
            </view>
            
            <view class="form-actions">
              <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
              <button type="submit" class="btn btn-primary">
                {{ editingPlan ? '保存' : '创建' }}
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { ref, computed, onMounted } from 'vue'

export default {
  name: 'StudyPlan',
  setup() {
    
    // 状态管理
    const currentPlan = ref(null)
    const historicalPlans = ref([])
    const availableWordSets = ref([])
    const showCreateModal = ref(false)
    const showEditModal = ref(false)
    const editingPlan = ref(null)
    
    // 学习统计数据
    const streakCount = ref(0)
    const totalWordsLearned = ref(0)
    const totalStudyHours = ref(0)
    
    // 表单数据
    const formData = ref({
      name: '',
      description: '',
      wordSetId: '',
      dailyTarget: 20,
      startDate: new Date().toISOString().split('T')[0],
      endDate: ''
    })
    
    // 计算当前计划的进度
    const planProgress = computed(() => {
      if (!currentPlan.value || !currentPlan.value.totalWords) return 0
      
      const learnedWords = currentPlan.value.learnedWords || 0
      return Math.min(Math.round((learnedWords / currentPlan.value.totalWords) * 100), 100)
    })
    
    // 初始化数据
    const initializeData = async () => {
      try {
        // 获取学习计划数据（模拟）
        await initializePlans()
        // 获取可用单词集（模拟）
        await initializeWordSets()
        // 获取学习统计数据
        await initializeStats()
      } catch (error) {
        console.error('初始化数据失败', error)
      }
    }
    
    // 初始化学习计划数据
    const initializePlans = async () => {
      try {
        // 模拟数据 - 实际项目中应从API获取
        const mockData = generateMockPlans()
        currentPlan.value = mockData.currentPlan
        historicalPlans.value = mockData.historicalPlans
        
        // 实际API调用代码
        // const response = await studyPlanAPI.getStudyPlans({ status: 'active' })
        // if (response.data && response.data.length > 0) {
        //   currentPlan.value = response.data[0]
        // }
        // 
        // const historicalResponse = await studyPlanAPI.getStudyPlans({ status: ['completed', 'paused'] })
        // historicalPlans.value = historicalResponse.data || []
      } catch (error) {
        console.error('获取学习计划失败', error)
      }
    }
    
    // 初始化可用单词集
    const initializeWordSets = async () => {
      try {
        // 模拟数据 - 实际项目中应从API获取
        availableWordSets.value = generateMockWordSets()
        
        // 实际API调用代码
        // const response = await wordSetAPI.getWordSets()
        // availableWordSets.value = response.data || []
      } catch (error) {
        console.error('获取单词集失败', error)
      }
    }
    
    // 初始化学习统计数据
    const initializeStats = () => {
      // 模拟数据
      streakCount.value = 7
      totalWordsLearned.value = 1250
      totalStudyHours.value = 35
    }
    
    // 生成模拟学习计划数据
    const generateMockPlans = () => {
      return {
        currentPlan: {
          id: 1,
          name: '托福词汇学习计划',
          description: '30天掌握托福核心词汇，每天学习20个单词',
          wordSetId: 1,
          wordSetName: '托福核心词汇',
          dailyTarget: 20,
          totalWords: 500,
          learnedWords: 140,
          startDate: '2023-12-01T00:00:00Z',
          endDate: '2023-12-30T00:00:00Z',
          status: 'active',
          completedDays: 7
        },
        historicalPlans: [
          {
            id: 2,
            name: '日常英语会话计划',
            description: '学习生活中常用的英语会话词汇',
            wordSetId: 2,
            wordSetName: '日常英语会话',
            dailyTarget: 15,
            totalWords: 300,
            learnedWords: 300,
            startDate: '2023-10-15T00:00:00Z',
            endDate: '2023-11-14T00:00:00Z',
            status: 'completed',
            completedDays: 25
          },
          {
            id: 3,
            name: '商务英语提升计划',
            description: '提升商务场合的英语词汇量和表达能力',
            wordSetId: 3,
            wordSetName: '商务英语词汇',
            dailyTarget: 25,
            totalWords: 450,
            learnedWords: 200,
            startDate: '2023-09-01T00:00:00Z',
            endDate: null,
            status: 'paused',
            completedDays: 8
          }
        ]
      }
    }
    
    // 生成模拟单词集数据
    const generateMockWordSets = () => {
      return [
        { id: 1, name: '托福核心词汇', wordCount: 500 },
        { id: 2, name: '日常英语会话', wordCount: 300 },
        { id: 3, name: '商务英语词汇', wordCount: 450 },
        { id: 4, name: '旅游英语常用词', wordCount: 200 },
        { id: 5, name: '计算机专业词汇', wordCount: 600 }
      ]
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '至今'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      })
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'active': '进行中',
        'paused': '已暂停',
        'completed': '已完成',
        'draft': '草稿'
      }
      return statusMap[status] || status
    }
    
    // 编辑当前计划
    const editCurrentPlan = () => {
      if (!currentPlan.value) return
      
      editingPlan.value = currentPlan.value
      formData.value = {
        name: currentPlan.value.name,
        description: currentPlan.value.description || '',
        wordSetId: currentPlan.value.wordSetId.toString(),
        dailyTarget: currentPlan.value.dailyTarget,
        startDate: new Date(currentPlan.value.startDate).toISOString().split('T')[0],
        endDate: currentPlan.value.endDate ? new Date(currentPlan.value.endDate).toISOString().split('T')[0] : ''
      }
      showEditModal.value = true
    }
    
    // 保存学习计划
    const savePlan = async () => {
      try {
        if (editingPlan.value) {
          // 编辑学习计划
          // const response = await studyPlanAPI.updateStudyPlan(editingPlan.value.id, formData.value)
          
          // 模拟更新成功
          currentPlan.value = {
            ...currentPlan.value,
            ...formData.value,
            wordSetId: parseInt(formData.value.wordSetId)
          }
        } else {
          // 创建新学习计划
          // const response = await studyPlanAPI.createStudyPlan(formData.value)
          
          // 模拟创建成功
          const newPlan = {
            id: Date.now(), // 模拟ID
            ...formData.value,
            wordSetId: parseInt(formData.value.wordSetId),
            wordSetName: availableWordSets.value.find(ws => ws.id === parseInt(formData.value.wordSetId))?.name,
            totalWords: 500, // 模拟数据
            learnedWords: 0,
            status: 'active',
            completedDays: 0
          }
          
          // 如果当前没有进行中的计划，则设为当前计划
          if (!currentPlan.value) {
            currentPlan.value = newPlan
          } else {
            // 否则添加到历史计划
            historicalPlans.value.push(newPlan)
          }
        }
        
        closeModal()
      } catch (error) {
        console.error(editingPlan.value ? '更新学习计划失败' : '创建学习计划失败', error)
      }
    }
    
    // 关闭模态框
    const closeModal = () => {
      showCreateModal.value = false
      showEditModal.value = false
      editingPlan.value = null
      formData.value = {
        name: '',
        description: '',
        wordSetId: '',
        dailyTarget: 20,
        startDate: new Date().toISOString().split('T')[0],
        endDate: ''
      }
    }
    
    // 开始今日学习
    const startTodayStudy = () => {
      if (currentPlan.value) {
        uni.navigateTo({
          url: `/pages/word-learning/WordLearning?planId=${currentPlan.value.id}&wordSetId=${currentPlan.value.wordSetId}`
        })
      }
    }
    
    // 暂停计划
    const pausePlan = async () => {
      if (currentPlan.value) {
        uni.showModal({
          title: '确认暂停',
          content: '确定要暂停当前学习计划吗？',
          success: (res) => {
            if (res.confirm) {
        try {
          // 模拟暂停成功
          currentPlan.value.status = 'paused'
          historicalPlans.value.push({ ...currentPlan.value })
          currentPlan.value = null
        } catch (error) {
          console.error('暂停计划失败', error)
        }
            }
          }
        })
      }
    }
    
    // 继续计划
    const resumePlan = async () => {
      if (currentPlan.value) {
        try {
          // 实际API调用代码
          // await studyPlanAPI.changePlanStatus(currentPlan.value.id, 'active')
          
          // 模拟继续成功
          currentPlan.value.status = 'active'
        } catch (error) {
          console.error('继续计划失败', error)
        }
      }
    }
    
    // 查看计划详情
    const viewPlanDetail = (planId) => {
      uni.navigateTo({
        url: `/pages/study-plan-detail/StudyPlanDetail?id=${planId}`
      })
    }
    
    // 组件挂载时初始化
    onMounted(() => {
      initializeData()
    })
    
    return {
      currentPlan,
      historicalPlans,
      availableWordSets,
      showCreateModal,
      showEditModal,
      editingPlan,
      formData,
      streakCount,
      totalWordsLearned,
      totalStudyHours,
      planProgress,
      formatDate,
      getStatusText,
      editCurrentPlan,
      savePlan,
      closeModal,
      startTodayStudy,
      pausePlan,
      resumePlan,
      viewPlanDetail
    }
  }
}
</script>

<style scoped>
.study-plan-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header h1 {
  color: #333;
  margin: 0;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-primary:hover {
  background-color: #2980b9;
}

.btn-secondary {
  background-color: #95a5a6;
  color: white;
}

.btn-secondary:hover {
  background-color: #7f8c8d;
}

/* 统计卡片样式 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 50px;
  height: 50px;
  background-color: #3498db;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 学习计划区域样式 */
.current-plan-section,
.historical-plans-section {
  margin-bottom: 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  color: #333;
  margin: 0;
}

.current-plan-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.plan-info h3 {
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-size: 20px;
}

.plan-description {
  color: #666;
  margin: 0 0 15px 0;
  line-height: 1.6;
}

.plan-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 25px;
}

.plan-daily-target {
  font-size: 14px;
  color: #555;
}

.plan-status {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.plan-status.active {
  background-color: #d4edda;
  color: #155724;
}

.plan-status.paused {
  background-color: #fff3cd;
  color: #856404;
}

.plan-status.completed {
  background-color: #cce5ff;
  color: #004085;
}

.plan-progress {
  margin-bottom: 25px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
  color: #555;
}

.progress-bar {
  height: 8px;
  background-color: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #4CAF50;
  transition: width 0.3s ease;
}

.plan-actions {
  display: flex;
  gap: 15px;
}

/* 历史计划列表样式 */
.plan-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.plan-item {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.plan-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.12);
}

.plan-item-info {
  flex: 1;
  margin-right: 20px;
}

.plan-item-info h3 {
  color: #2c3e50;
  margin: 0 0 8px 0;
  font-size: 16px;
}

.plan-item-description {
  color: #666;
  margin: 0 0 10px 0;
  font-size: 14px;
  line-height: 1.5;
}

.plan-item-meta {
  display: flex;
  gap: 20px;
}

.plan-item-period {
  font-size: 12px;
  color: #999;
}

.plan-item-status {
  padding: 3px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.plan-item-status.active {
  background-color: #d4edda;
  color: #155724;
}

.plan-item-status.paused {
  background-color: #fff3cd;
  color: #856404;
}

.plan-item-status.completed {
  background-color: #cce5ff;
  color: #004085;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h2 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-group input,
.form-group textarea,
.form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s ease;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
  outline: none;
  border-color: #3498db;
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .current-plan-card {
    padding: 20px;
  }
  
  .plan-meta {
    flex-direction: column;
    gap: 10px;
  }
  
  .plan-actions {
    flex-direction: column;
  }
  
  .plan-item {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
  
  .plan-item-info {
    margin-right: 0;
  }
  
  .section-header {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }
}
</style>